#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
CML Config 使用示例
演示如何在Qt应用中使用XML配置系统
"""

import sys
import os
from PyQt5.QtWidgets import QApplication, QMainWindow, QTextEdit
from PyQt5.QtCore import Qt

# 添加父目录到路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from xmlconfig import MenuToolbarParser, ActionRegistry, DefaultActionHandler
from xmlconfig.icon_manager import IconManager
from xmlconfig.theme_manager import ThemeManager


class ExampleWindow(QMainWindow):
    """示例主窗口"""
    
    def __init__(self):
        super().__init__()
        self.icon_manager = None
        self.theme_manager = None
        self.parser = None
        self.init_ui()
        self.setup_menu_toolbar()
    
    def init_ui(self):
        """初始化UI"""
        self.setWindowTitle('CML Config 示例')
        self.resize(800, 600)
        
        # 中央控件
        self.text_edit = QTextEdit()
        self.text_edit.setPlaceholderText('使用菜单和工具栏测试功能...')
        self.setCentralWidget(self.text_edit)
        
        # 状态栏
        self.statusBar().showMessage('就绪')
    
    def setup_menu_toolbar(self):
        """配置菜单和工具栏"""
        # 创建action注册表
        registry = ActionRegistry()
        
        # 创建图标管理器(暗色主题)
        self.icon_manager = IconManager(theme='dark')
        
        # 创建主题管理器
        self.theme_manager = ThemeManager(QApplication.instance(), self.icon_manager)
        
        # 创建自定义action处理器
        handler = CustomActionHandler(registry, self)
        
        # 获取XML配置文件路径
        config_path = os.path.join(
            os.path.dirname(__file__),
            'menu_toolbar_config.xml'
        )
        
        # 获取样式文件路径
        style_path = os.path.join(
            os.path.dirname(__file__),
            'toolbar_style.qss'
        )
        
        # 创建解析器(传入图标管理器)
        self.parser = MenuToolbarParser(
            config_path, 
            registry.get_all(), 
            style_path,
            self.icon_manager
        )
        
        # 解析XML
        if self.parser.parse():
            # 构建菜单栏
            self.parser.build_menubar(self.menuBar())
            
            # 构建工具栏
            self.parser.build_toolbars(self)
            
            # 绑定parser到theme_manager（用于主题切换时更新图标）
            self.theme_manager.set_parser(self.parser)
            
            # 设置主题动作组(互斥)
            theme_actions = {
                'theme_dark': self.parser.get_action('theme_dark'),
                'theme_light': self.parser.get_action('theme_light')
            }
            self.theme_manager.create_theme_action_group(theme_actions)
            
            self.log("菜单和工具栏加载成功(已应用图标和样式)")
        else:
            self.log("加载菜单配置失败")
    
    def log(self, message):
        """输出日志到文本框"""
        self.text_edit.append(f"[LOG] {message}")
        self.statusBar().showMessage(message, 3000)


class CustomActionHandler(DefaultActionHandler):
    """自定义Action处理器"""
    
    def __init__(self, registry, window):
        self.window = window
        super().__init__(registry)
    
    # 重写部分方法以实现实际功能
    def on_new_project(self):
        self.window.log("新建项目...")
        self.window.text_edit.clear()
    
    def on_open_project(self):
        self.window.log("打开项目...")
    
    def on_save(self):
        self.window.log("保存文件...")
    
    def on_exit(self):
        self.window.log("退出应用...")
        self.window.close()
    
    def on_undo(self):
        self.window.log("撤销操作")
        self.window.text_edit.undo()
    
    def on_redo(self):
        self.window.log("重做操作")
        self.window.text_edit.redo()
    
    def on_cut(self):
        self.window.log("剪切")
        self.window.text_edit.cut()
    
    def on_copy(self):
        self.window.log("复制")
        self.window.text_edit.copy()
    
    def on_paste(self):
        self.window.log("粘贴")
        self.window.text_edit.paste()
    
    def on_zoom_in(self):
        self.window.log("放大")
        self.window.text_edit.zoomIn(2)
    
    def on_zoom_out(self):
        self.window.log("缩小")
        self.window.text_edit.zoomOut(2)
    
    def on_zoom_reset(self):
        self.window.log("重置缩放")
        self.window.text_edit.setFont(QApplication.font())
    
    def on_toggle_fullscreen(self, checked):
        self.window.log(f"全屏模式: {'开启' if checked else '关闭'}")
        if checked:
            self.window.showFullScreen()
        else:
            self.window.showNormal()
    
    def on_view_selector_changed(self, index):
        views = ['原理图', 'PCB', '3D视图']
        if 0 <= index < len(views):
            self.window.log(f"切换到 {views[index]} 视图")
    
    def on_schematic_editor(self):
        self.window.log("打开原理图编辑器")
    
    def on_pcb_editor(self):
        self.window.log("打开PCB编辑器")
    
    def on_about(self):
        self.window.log("关于：CML Config - XML驱动的菜单工具栏配置系统")
    
    # 主题切换
    def on_theme_dark(self, checked):
        if checked and self.window.theme_manager:
            self.window.log("切换到暗色主题")
            self.window.theme_manager.set_theme('dark')
            # 重新应用工具栏样式
            self._reapply_toolbar_styles()
    
    def on_theme_light(self, checked):
        if checked and self.window.theme_manager:
            self.window.log("切换到亮色主题")
            self.window.theme_manager.set_theme('light')
            # 重新应用工具栏样式
            self._reapply_toolbar_styles()
    
    def _reapply_toolbar_styles(self):
        """重新应用工具栏样式"""
        if self.window.parser and self.window.parser.stylesheet:
            for toolbar in self.window.parser.toolbars.values():
                toolbar.setStyleSheet(self.window.parser.stylesheet)


def main():
    """主函数"""
    app = QApplication(sys.argv)
    
    # 设置应用信息
    app.setApplicationName('CML Config Demo')
    app.setOrganizationName('Example')
    
    # 创建主窗口
    window = ExampleWindow()
    window.show()
    
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
